package com.part.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tedu.pj.common.annotation.RequiredLog;
import com.tedu.pj.common.util.IPUtils;
import com.tedu.pj.sys.pojo.SysLog;
import com.tedu.pj.sys.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/10/16
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.tedu.pj.common.annotation.RequiredLog)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint jointPoint) throws Throwable {
        try {
            long startTime = System.currentTimeMillis();
            Object result = jointPoint.proceed();
            long endTime = System.currentTimeMillis();
            long totalTime = endTime - startTime;
            log.info("方法执行的总时长为:{}", totalTime);
            saveSysLog(jointPoint, totalTime);
            return result;
        }catch (Exception e){
            logError(jointPoint,e);
            throw e;
        }
    }

    void saveSysLog(ProceedingJoinPoint point, long totleTime) throws NoSuchMethodException,
            SecurityException, JsonProcessingException {
        MethodSignature ms = (MethodSignature) point.getSignature();
        Class<?> targetClass = point.getTarget().getClass();
        String className = targetClass.getName();
        String methodName = ms.getMethod().getName();
        Class<?>[] parameterTypes = ms.getMethod().getParameterTypes();
        Method targetMethod = targetClass.getDeclaredMethod(methodName, parameterTypes);
       // String username = ShiroUtils.getPrincipal().getUsername();
        SysLog log = new SysLog();
        log.setUsername("root");
        RequiredLog requestLog = targetMethod.getDeclaredAnnotation(RequiredLog.class);
        if (requestLog != null) {
            log.setOperation(requestLog.value());
        }
        log.setMethod(className + "." + methodName);

        Object[] paramsObj = point.getArgs();
        String params = new ObjectMapper().writeValueAsString(paramsObj);
        log.setParams(params);

        log.setIp(IPUtils.getIpAddr());
        log.setTime(totleTime);
        log.setCreatedTime(new Date());
        sysLogService.saveObject(log);
    }

    void logError(ProceedingJoinPoint point,Throwable e) throws JsonProcessingException {
        log.error("error ->{} ->{} ->{}",
                point.getTarget().getClass() + "." + point.getSignature().getName(),
                new ObjectMapper().writeValueAsString(point.getArgs()),
                e.getMessage()
        );
    }

}
